# -*- coding;utf-8 -*-
"""
File name : TokenQINIU.py.PY
Program IDE : PyCharm
Create file time: 2024/3/30 7:46
File Create By Author : 朱清闯
"""
from qiniu import Auth, etag, urlsafe_base64_encode
from django.conf import settings
from datetime import datetime
from random import randint
import qiniu.config


def get_token(url='', suffix='.mp4', question=0):
    # 需要填写你的 Access Key 和 Secret Key
    access_key = settings.ACCESSKEY_QINIU
    secret_key = settings.SECRETKEY_QINIU

    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'xxjstktop'
    # 上传后保存的文件名
    if url == '':
        url = str(datetime.now()) + str(randint(10000, 99999)) + suffix
    callback_body = "key=$(key)&hash=$(etag)&fsize=$(fsize)&mimeType=$(mimeType)&question=$(x:question)&owner=$(x:owner)"
    # 生成上传 Token，可以指定过期时间等
    # 上传策略示例
    # https://developer.qiniu.com/kodo/manual/1206/put-policy
    policy = {
        'scope': bucket_name,
        'callbackUrl': 'https://xxjstk.top/api/VideoModelViewSet/create_question_video/',
        'callbackBody': callback_body,
        # 'persistentOps':'imageView2/1/w/200/h/200'
    }
    # 将policy进行base64编码
    # encoded_policy = urlsafe_base64_encode(qiniu.utils.urlsafe_base64_encode(policy))
    # print('get_token policy:', encoded_policy)

    # 3600为token过期时间，秒为单位。3600等于一小时, 难道自带缓存功能？
    token = q.upload_token(bucket=bucket_name, key=url, expires=3600, policy=policy)
    # token = q.upload_token(bucket_name, url, 3600, policy)
    return token
